﻿<script lang="ts" name="sysreturnorder" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { generateReturnOrderCode } from '/@/utils/generateCode';
import { useSysreturnorderApi } from '/@/api/order/sysreturnorder';
import { useSysOrgApi } from '/@/api/system/sysOrg';
import { useSysUserApi } from '/@/api/system/sysUser';
import { useSyspurchaseorderApi } from '/@/api/order/syspurchaseorder';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const sysreturnorderApi = useSysreturnorderApi();
const sysOrgApi = useSysOrgApi();
const sysUserApi = useSysUserApi();
const syspurchaseorderApi = useSyspurchaseorderApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	// 下拉框数据
	orgList: [] as any[],
	userList: [] as any[],
	filteredUserList: [] as any[], // 根据部门筛选后的用户列表
	// 进货订单列表
	purchaseOrderList: [] as any[],
});

// 自行添加其他规则
const rules = ref<FormRules>({
  code: [{required: true, message: '请选择退货单号！', trigger: 'blur',},],
  documentStatus: [{required: true, message: '请选择单据状态！', trigger: 'blur',},],
  returnDate: [{required: true, message: '请选择退货日期！', trigger: 'change',},],
});

// 监听进货单号变化，自动填充相关信息
const onPurchaseOrderChange = (purchaseOrderCode: string) => {
	if (purchaseOrderCode) {
		const selectedOrder = state.purchaseOrderList.find(order => order.code === purchaseOrderCode);
		if (selectedOrder) {
			// 自动填充进货订单相关信息
			state.ruleForm.supplier = selectedOrder.supplier;
			state.ruleForm.contactPerson = selectedOrder.contactPerson;
			state.ruleForm.contactMethod = selectedOrder.contactMethod;
			state.ruleForm.purchaseDeptId = selectedOrder.purchaseDeptId;
			state.ruleForm.purchaserId = selectedOrder.purchaserId;
			// 自动填充退货数量（直接等于进货数量）
			state.ruleForm.returnQuantity = selectedOrder.itemQuantity || 0;
			
			// 根据进货部门过滤用户列表，但保持进货负责人选择
			onDeptChange(selectedOrder.purchaseDeptId, true);
		}
	} else {
		// 清空相关信息
		state.ruleForm.supplier = '';
		state.ruleForm.contactPerson = '';
		state.ruleForm.contactMethod = '';
		state.ruleForm.purchaseDeptId = null;
		state.ruleForm.purchaserId = null;
		state.ruleForm.returnQuantity = 0;
	}
};

// 部门变化时筛选用户
const onDeptChange = (deptId: number, keepPurchaser: boolean = false) => {
	if (deptId) {
		// 根据部门ID筛选用户
		state.filteredUserList = state.userList.filter(user => user.orgId === deptId);
	} else {
		// 如果没有选择部门，显示所有用户
		state.filteredUserList = state.userList;
	}
	// 只有在不是从进货单号反填时才清空已选择的负责人
	if (!keepPurchaser) {
		state.ruleForm.purchaserId = null;
	}
};

// 转换状态为中文显示
const convertStatusToChinese = (status: any) => {
	const statusMap: { [key: string]: string } = {
		// 数字状态码
		'1': '草稿',
		'2': '待审核', 
		'3': '驳回',
		'4': '未出库',  // 进货退货订单状态4应该是未出库
		'6': '已完成',
		'7': '已关闭',
		// 枚举状态码
		'Draft': '草稿',
		'PendingReview': '待审核',
		'Rejected': '驳回',
		'NotOutOfWarehouse': '未出库',  // 进货退货的NotOutOfWarehouse应该是未出库
		'Completed': '已完成',
		'Closed': '已关闭',
		// 中文状态值（进货退货订单使用）
		'草稿': '草稿',
		'待审核': '待审核',
		'驳回': '驳回',
		'未出库': '未出库',
		'已完成': '已完成',
		'已关闭': '已关闭'
	};
	return statusMap[status] || status;
};

// 转换中文状态为后端格式
const convertStatusToBackend = (status: any) => {
	const statusMap: { [key: string]: number } = {
		'草稿': 1,
		'待审核': 2,
		'驳回': 3,
		'未出库': 4,
		'已完成': 6,
		'已关闭': 7
	};
	return statusMap[status] || status;
};

// 加载进货订单列表
const loadPurchaseOrderList = async () => {
	try {
		const res = await syspurchaseorderApi.page({ page: 1, pageSize: 9999 });
		state.purchaseOrderList = res.data.result?.items || [];
	} catch (error) {
		console.error('加载进货订单列表失败:', error);
	}
};

// 页面加载时
onMounted(async () => {
	// 加载机构列表
	try {
		const orgRes = await sysOrgApi.getList();
		state.orgList = orgRes.data.result || [];
	} catch (error) {
		console.error('加载机构列表失败:', error);
	}
	
	// 加载用户列表
	try {
		const userRes = await sysUserApi.getList();
		state.userList = userRes.data.result || [];
		state.filteredUserList = userRes.data.result || []; // 初始显示所有用户
	} catch (error) {
		console.error('加载用户列表失败:', error);
	}

	// 加载进货订单列表
	await loadPurchaseOrderList();
});

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {};
	
	if (row.id) {
		// 编辑模式：获取完整数据
		state.ruleForm = await sysreturnorderApi.detail(row.id).then(res => res.data.result);
		
		// 转换单据状态为中文显示
		state.ruleForm.documentStatus = convertStatusToChinese(state.ruleForm.documentStatus);
		
		// 如果退货数量为空，尝试从进货订单获取
		if (!state.ruleForm.returnQuantity && state.ruleForm.purchaseOrderNumber) {
			const selectedOrder = state.purchaseOrderList.find(order => order.code === state.ruleForm.purchaseOrderNumber);
			if (selectedOrder) {
				state.ruleForm.returnQuantity = selectedOrder.itemQuantity || 0;
			}
		}
	} else {
		// 新增模式：初始化表单数据，确保必填字段有默认值
		state.ruleForm = {
			code: generateReturnOrderCode(), // 退货单号 - 自动生成
			documentStatus: '草稿', // 默认状态
			returnDate: new Date(), // 退货日期
			purchaseOrderNumber: '', // 进货单号
			supplier: '', // 供应商
			contactPerson: '', // 联系人
			contactMethod: '', // 联系方式
			purchaseDeptId: null, // 进货部门ID
			purchaserId: null, // 进货人ID
			returnQuantity: 0, // 退货数量，默认为0
			returnReason: '', // 退货原因
			remark: '', // 备注
			createUserId: 1300000000001, // 任杰的用户ID
			createUserName: "任杰", // 任杰的用户名
		};
	}
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			// 额外验证必填字段
			if (!state.ruleForm.code || state.ruleForm.code.trim() === '') {
				ElMessage.error('退货单号不能为空！');
				return;
			}
			if (!state.ruleForm.returnQuantity || state.ruleForm.returnQuantity <= 0) {
				ElMessage.error('退货数量必须大于0！');
				return;
			}
			
			try {
				let values = { ...state.ruleForm };
				// 转换中文状态为后端需要的格式
				values.documentStatus = convertStatusToBackend(values.documentStatus);
				await sysreturnorderApi[state.ruleForm.id ? 'update' : 'add'](values);
				ElMessage.success(state.ruleForm.id ? '更新成功！' : '新增成功！');
				closeDialog();
			} catch (error: any) {
				console.error('提交失败:', error);
				ElMessage.error('提交失败：' + (error.message || '未知错误'));
			}
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="sysreturnorder-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="退货单号" prop="code">
							<el-input 
								v-model="state.ruleForm.code" 
								placeholder="退货单号" 
								maxlength="64" 
								show-word-limit 
								:readonly="true"
								style="background-color: #f5f7fa;"
							/>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="单据状态" prop="documentStatus">
							<el-select v-model="state.ruleForm.documentStatus" placeholder="请选择单据状态" clearable filterable style="width: 100%">
								<el-option label="草稿" value="草稿" />
								<el-option label="待审核" value="待审核" />
								<el-option label="驳回" value="驳回" />
								<el-option label="未出库" value="未出库" />							
								<el-option label="已完成" value="已完成" />
								<el-option label="已关闭" value="已关闭" />
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="退货日期" prop="returnDate">
							<el-date-picker v-model="state.ruleForm.returnDate" type="date" placeholder="退货日期" />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="进货单号" prop="purchaseOrderNumber">
							<el-select 
								v-model="state.ruleForm.purchaseOrderNumber" 
								placeholder="请选择进货单号" 
								clearable 
								filterable
								style="width: 100%"
								@change="onPurchaseOrderChange"
							>
								<el-option
									v-for="order in state.purchaseOrderList"
									:key="order.id"
									:label="order.code"
									:value="order.code"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="供应商" prop="supplier">
							<el-input 
								v-model="state.ruleForm.supplier" 
								placeholder="供应商" 
								maxlength="128" 
								show-word-limit 
								:readonly="true"
								style="background-color: #f5f7fa;"
							/>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="联系人" prop="contactPerson">
							<el-input v-model="state.ruleForm.contactPerson" placeholder="请输入联系人" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="联系方式" prop="contactMethod">
							<el-input v-model="state.ruleForm.contactMethod" placeholder="请输入联系方式" maxlength="32" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="进货部门" prop="purchaseDeptId">
							<el-select v-model="state.ruleForm.purchaseDeptId" placeholder="请选择进货部门" clearable filterable @change="(deptId) => onDeptChange(deptId, false)">
								<el-option
									v-for="org in state.orgList"
									:key="org.id"
									:label="org.name"
									:value="org.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="进货人" prop="purchaserId">
							<el-select v-model="state.ruleForm.purchaserId" placeholder="请选择进货人" clearable filterable>
								<el-option
									v-for="user in state.filteredUserList"
									:key="user.id"
									:label="user.realName"
									:value="user.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="退货数量" prop="returnQuantity">
							<el-input 
								v-model="state.ruleForm.returnQuantity" 
								placeholder="退货数量" 
								:readonly="true"
								style="background-color: #f5f7fa; color: #606266;"
							/>
							<div style="font-size: 12px; color: #909399; margin-top: 4px;">
								系统自动填充，不可修改
							</div>
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="退货原因" prop="returnReason">
							<el-input v-model="state.ruleForm.returnReason" placeholder="请输入退货原因" maxlength="256" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="512" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>